﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using DM4;
using sscore;
using DevExpress.XtraGrid.Views.Base;
using DM4Script;
using sscore.Utils;

namespace DM4Client
{
    public partial class FrmMain
    {
        #region Form Handlers

        private void rbiScriptDeleteItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DeleteScript();
        }

        private void DgScriptsFocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            RefreshOneScript();
        }

        private void rbiScriptRefreshItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RefreshScripts();
        }

        private void rbiScriptAddItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            AddEditScript(false);
        }

        private void rbiScriptEditItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            AddEditScript();
        }
        #endregion Form Handlers

        private void rbiScriptCheckItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            _stbScriptLog.Text = "";

            if (!String.IsNullOrEmpty(_stbScriptInfoScript.Text))
            {
                var parse = new ScriptParse();
                parse.Analize(_stbScriptInfoScript.Text);
                foreach (var log in parse.Logs)
                {
                    _stbScriptLog.Text += log.Message() + "\n";
                    //if (log._error)
                    //{
                    //    StbScriptLog.SelectAll();
                    //    StbScriptLog.SelectionColor = Color.Red;

                    //    if (log._selectError != null)
                    //    {
                    //        StbScriptInfo.Select(log._selectError.x, 3);
                    //        StbScriptInfo.SelectionBackColor = Color.Red;
                    //    }

                    //}
                }
            }
        }

        protected void AddEditScript(bool edit = true)
        {
            DataRow drs = _fScripts.gvScripts.GetDataRow(_fScripts.gvScripts.FocusedRowHandle);
            if (edit && drs == null) return;

            int scrId = edit ? SysUtils.ConvertFromDBVal<int>(drs["scr_id"]) : DM4Consts.DefaultNULLId;

            if (_fScripts.gvScripts.FocusedRowHandle == DevExpress.XtraGrid.GridControl.InvalidRowHandle && edit) return;

            using (AddEditForms.FrmAddEditScript frmAddEdit = new AddEditForms.FrmAddEditScript(scrId))
            {
                DialogResult dr = frmAddEdit.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    if (!edit)
                        scrId = frmAddEdit.Result.Result;

                    RefreshScripts(scrId);
                }
            }
        }

        private void DeleteScript()
        {
            if (_fScripts.gvScripts.FocusedRowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
            {
                DataRow drs = _fScripts.gvScripts.GetDataRow(_fScripts.gvScripts.FocusedRowHandle);
                int scrId = SysUtils.ConvertFromDBVal<int>(drs["scr_id"]);

                if (MessageBox.Show(this, String.Format("Delete script with id {0}?", scrId), "Delete script",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                    return;

                OperationResult or = DeleteScript(scrId);

                if (or.Result != DM4Consts.Ok)
                    MessageBox.Show(this, or.Message, DmConsts.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show(this, "Script deleted", "Delete script", MessageBoxButtons.OK, MessageBoxIcon.Information);

                RefreshScripts();
            }
        }

        private void RefreshScripts(int scrId = DM4Consts.DefaultNULLId)
        {
            _fScripts.gvScripts.FocusedRowChanged -= DgScriptsFocusedRowChanged;

            try
            {
                int id = DM4Consts.DefaultNULLId;
                if (scrId == DM4Consts.DefaultNULLId)
                {

                    if (_fScripts.gvScripts.RowCount > 0)
                    {
                        DataRow drs = _fScripts.gvScripts.GetDataRow(_fScripts.gvScripts.FocusedRowHandle);
                        id = SysUtils.ConvertFromDBVal<int>(drs["scr_id"]);
                    }
                }
                else
                    id = scrId;

                try
                {
                    _fScripts.dgScripts.DataSource = null;

                    XMLInfo xi = GetScriptList();
                    DtScripts = XMLInfo.FillTable(xi, DtScripts);

                    _fScripts.dgScripts.DataMember = DtScripts.TableName;
                    _fScripts.dgScripts.DataSource = DtScripts;

                    _fScripts.gvScripts.BeginUpdate();
                    try
                    {
                        int rowHandle = _fScripts.gvScripts.LocateByValue("scr_id", id);
                        // exiting the loop if no row is found 
                        if (rowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
                            _fScripts.gvScripts.FocusedRowHandle = rowHandle;
                        else
                            if (_fScripts.gvScripts.RowCount > 0)
                                _fScripts.gvScripts.MoveFirst();

                        RefreshOneScript();

                    }
                    finally
                    {
                        _fScripts.gvScripts.EndUpdate();
                    }

                    RefreshOneScript();

                    UpdateMainControlsState();
                }
                catch (Exception ex)
                {
                    //SERVER IS DOWN!! NEED RECONNECT                   
                    WriteError(ex.Message);
                    LoginToService();
                }
            }
            finally
            {
                _fScripts.gvScripts.FocusedRowChanged += DgScriptsFocusedRowChanged;
            }
        }

        private void RefreshOneScript()
        {
            //get datarow           
            int rowHandle = _fScripts.gvScripts.FocusedRowHandle;
            DataRow drs = _fScripts.gvScripts.GetDataRow(rowHandle);

            //fill script info table 
            ShowScriptInfo(drs);

            UpdateMainControlsState();
        }

        private void ShowScriptInfo(DataRow drs)
        {
            //fill script info table 
            dsInfo.Tables["dtScriptInfo"].Rows.Clear();

            if (drs == null) return;

            DataRow dr = dsInfo.Tables["dtScriptInfo"].NewRow();
            dr["Name"] = "Script Id";
            dr["Value"] = drs["scr_id"];
            dsInfo.Tables["dtScriptInfo"].Rows.Add(dr);

            dr = dsInfo.Tables["dtScriptInfo"].NewRow();
            dr["Name"] = "Name";
            dr["Value"] = drs["scr_name"];
            dsInfo.Tables["dtScriptInfo"].Rows.Add(dr);

            dr = dsInfo.Tables["dtScriptInfo"].NewRow();
            dr["Name"] = "Description";
            dr["Value"] = drs["scr_description"];
            dsInfo.Tables["dtScriptInfo"].Rows.Add(dr);

            dr = dsInfo.Tables["dtScriptInfo"].NewRow();
            dr["Name"] = "Version";
            dr["Value"] = drs["scr_version"];
            dsInfo.Tables["dtScriptInfo"].Rows.Add(dr);

            dr = dsInfo.Tables["dtScriptInfo"].NewRow();
            dr["Name"] = "Created";
            dr["Value"] = drs["scr_created"];
            dsInfo.Tables["dtScriptInfo"].Rows.Add(dr);

            dr = dsInfo.Tables["dtScriptInfo"].NewRow();
            dr["Name"] = "Author";
            dr["Value"] = drs["scr_author_name"];
            dsInfo.Tables["dtScriptInfo"].Rows.Add(dr);

            dr = dsInfo.Tables["dtScriptInfo"].NewRow();
            dr["Name"] = "Last modified";
            dr["Value"] = drs["scr_last_modified"];
            dsInfo.Tables["dtScriptInfo"].Rows.Add(dr);

            dr = dsInfo.Tables["dtScriptInfo"].NewRow();
            dr["Name"] = "Modified by";
            dr["Value"] = drs["scr_last_modified_name"];
            dsInfo.Tables["dtScriptInfo"].Rows.Add(dr);

            //read script text
            _stbScriptInfoScript.Text = drs["scr_text"].ToString();
        }

        private void rbiScriptStartItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (_fScripts.gvScripts.FocusedRowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
            {
                DataRow drs = _fScripts.gvScripts.GetDataRow(_fScripts.gvScripts.FocusedRowHandle);
                int scrId = SysUtils.ConvertFromDBVal<int>(drs["scr_id"]);


                if (MessageBox.Show(this, String.Format("Run script with id {0}?", scrId), "Run script",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                    return;

                OperationResult or = RunScript(scrId);

                if (or.Result != DM4Consts.Ok)
                    MessageBox.Show(this, or.Message, DmConsts.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            
        }

     

    }
}
